<template>
  <div class="admin-venues">
    <h2>场馆管理</h2>
    
    <!-- 搜索和添加按钮 -->
    <el-row :gutter="20" style="margin-bottom: 20px;">
      <el-col :span="8">
        <el-input
          v-model="searchQuery"
          placeholder="搜索场馆名称"
          prefix-icon="el-icon-search"
          clearable
          @input="handleSearch"
        ></el-input>
      </el-col>
      <el-col :span="4">
        <el-button type="primary" @click="showAddDialog = true">添加场馆</el-button>
      </el-col>
    </el-row>

    <!-- 场馆列表 -->
    <el-table :data="filteredVenues" style="width: 100%">
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="name" label="场馆名称"></el-table-column>
      <el-table-column prop="address" label="地址"></el-table-column>
      <el-table-column prop="city" label="城市" width="100"></el-table-column>
      <el-table-column prop="capacity" label="容纳人数" width="120"></el-table-column>
      <el-table-column prop="phone" label="联系电话" width="150"></el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button size="small" @click="editVenue(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteVenue(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="dialogTitle"
      width="600px"
      @close="resetForm"
    >
      <el-form
        :model="venueForm"
        :rules="venueRules"
        ref="venueFormRef"
        label-width="100px"
      >
        <el-form-item label="场馆名称" prop="name">
          <el-input v-model="venueForm.name" placeholder="请输入场馆名称"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="venueForm.address" placeholder="请输入场馆地址"></el-input>
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-input v-model="venueForm.city" placeholder="请输入城市"></el-input>
        </el-form-item>
        <el-form-item label="容纳人数" prop="capacity">
          <el-input-number v-model="venueForm.capacity" :min="0" :step="1" placeholder="请输入容纳人数"></el-input-number>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="venueForm.phone" placeholder="请输入联系电话"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="venueForm.description"
            type="textarea"
            rows="3"
            placeholder="请输入场馆描述"
          ></el-input>
        </el-form-item>
        <el-form-item label="图片URL" prop="imageUrl">
          <el-input v-model="venueForm.imageUrl" placeholder="请输入图片URL"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import api from '../../api/index.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAppStore } from '../../store'

export default {
  name: 'AdminVenues',
  setup() {
    const router = useRouter()
    const store = useAppStore()
    const venues = ref([])
    const loading = ref(true)
    const searchQuery = ref('')
    const showAddDialog = ref(false)
    const venueForm = ref({
      id: null,
      name: '',
      address: '',
      city: '',
      capacity: 0,
      phone: '',
      description: '',
      imageUrl: ''
    })
    const venueFormRef = ref(null)
    const venueRules = {
      name: [{ required: true, message: '请输入场馆名称', trigger: 'blur' }],
      address: [{ required: true, message: '请输入场馆地址', trigger: 'blur' }],
      city: [{ required: true, message: '请输入城市', trigger: 'blur' }],
      capacity: [{ required: true, message: '请输入容纳人数', trigger: 'blur' }]
    }

    // 检查是否为管理员
    onMounted(() => {
      if (!store.isLoggedIn || !store.user?.is_admin) {
        ElMessage.error('需要管理员权限')
        router.push('/')
        return
      }
      fetchVenues()
    })

    // 获取所有场馆
    const fetchVenues = async () => {
      try {
        loading.value = true
        const response = await api.get('/venues')
        venues.value = response
      } catch (error) {
        console.error('获取场馆失败:', error)
        ElMessage.error('获取场馆失败')
      } finally {
        loading.value = false
      }
    }

    // 根据搜索条件过滤场馆
    const filteredVenues = computed(() => {
      if (!searchQuery.value.trim()) {
        return venues.value
      }
      const query = searchQuery.value.toLowerCase().trim()
      return venues.value.filter(venue => 
        venue.name.toLowerCase().includes(query)
      )
    })

    // 搜索处理
    const handleSearch = () => {
      // 搜索功能由computed属性自动处理
    }

    // 添加场馆
    const addVenue = async () => {
      try {
        // 验证并转换capacity为整数
        const capacityInt = parseInt(venueForm.value.capacity, 10);
        if (isNaN(capacityInt) || capacityInt <= 0) {
          ElMessage.error('容纳人数必须是有效的正整数');
          return;
        }
        
        // 创建提交数据，确保字段名正确转换
        const formData = {
          name: venueForm.value.name.trim(),
          address: venueForm.value.address.trim(),
          city: venueForm.value.city.trim(),
          capacity: capacityInt,  // 确保是整数类型
          phone: (venueForm.value.phone || '').trim(),
          image_url: (venueForm.value.imageUrl || '').trim()
        }
        
        console.log('提交的数据:', formData);
        console.log('capacity类型:', typeof formData.capacity);
        
        const response = await api.post('/venues', formData)
        // 添加成功后重新获取数据
        fetchVenues()
        ElMessage.success('添加成功')
        showAddDialog.value = false
      } catch (error) {
        console.error('添加场馆失败:', error)
        console.log('错误详情:', error.response?.data)
        ElMessage.error(error.response?.data?.message || error.response?.data?.error || '添加场馆失败')
      }
    }

    // 编辑场馆
    const updateVenue = async () => {
      try {
        const id = venueForm.value.id
        
        // 验证并转换capacity为整数
        const capacityInt = parseInt(venueForm.value.capacity, 10);
        if (isNaN(capacityInt) || capacityInt <= 0) {
          ElMessage.error('容纳人数必须是有效的正整数');
          return;
        }
        
        // 创建提交数据，确保字段名正确转换
        const formData = {
          name: venueForm.value.name.trim(),
          address: venueForm.value.address.trim(),
          city: venueForm.value.city.trim(),
          capacity: capacityInt,  // 确保是整数类型
          phone: (venueForm.value.phone || '').trim(),
          image_url: (venueForm.value.imageUrl || '').trim()
        }
        
        console.log('更新的数据:', formData);
        console.log('capacity类型:', typeof formData.capacity)
        
        const response = await api.put(`/venues/${id}`, formData)
        // 更新成功后重新获取数据
        fetchVenues()
        ElMessage.success('更新成功')
        showAddDialog.value = false
      } catch (error) {
        console.error('更新场馆失败:', error)
        console.log('错误详情:', error.response?.data)
        ElMessage.error(error.response?.data?.message || error.response?.data?.error || '更新场馆失败')
      }
    }

    // 打开编辑对话框
    const editVenue = (venue) => {
      venueForm.value = {
        id: venue.id,
        name: venue.name,
        address: venue.address,
        city: venue.city,
        capacity: venue.capacity,
        phone: venue.phone,
        description: venue.description,
        imageUrl: venue.imageUrl
      }
      showAddDialog.value = true
    }

    // 删除场馆
    const deleteVenue = (id) => {
      ElMessageBox.confirm('确定要删除这个场馆吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await api.delete(`/venues/${id}`)
          // 删除成功后重新获取数据
          fetchVenues()
          ElMessage.success('删除成功')
        } catch (error) {
          console.error('删除场馆失败:', error)
          ElMessage.error(error.response?.data?.error || '删除场馆失败')
        }
      }).catch(() => {
        // 取消删除
      })
    }

    // 提交表单
    const submitForm = async () => {
      await venueFormRef.value.validate((valid) => {
        if (valid) {
          if (venueForm.value.id) {
            updateVenue()
          } else {
            addVenue()
          }
        }
      })
    }

    // 重置表单
    const resetForm = () => {
      venueForm.value = {
        id: null,
        name: '',
        address: '',
        city: '',
        capacity: 0,
        phone: '',
        description: '',
        imageUrl: ''
      }
      venueFormRef.value?.resetFields()
    }

    // 对话框标题
    const dialogTitle = computed(() => {
      return venueForm.value.id ? '编辑场馆' : '添加场馆'
    })

    return {
      venues,
      loading,
      searchQuery,
      showAddDialog,
      venueForm,
      venueFormRef,
      venueRules,
      filteredVenues,
      dialogTitle,
      handleSearch,
      editVenue,
      deleteVenue,
      submitForm,
      resetForm
    }
  }
}
</script>

<style scoped>
.admin-venues {
  padding: 20px;
}

h2 {
  margin-bottom: 20px;
  color: #333;
}
</style>